//
//  DYAddContentTextCell.m
//  DaYing
//
//  Created by DaYing Team on 2023.
//  Copyright © 2023 DaYing Team. All rights reserved.
//

#import "DYAddContentTextCell.h"

@interface DYAddContentTextCell () <UITextViewDelegate>

@end

@implementation DYAddContentTextCell

+ (id)instanceView {
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
    return [nibView objectAtIndex:0];
}

- (void)awakeFromNib {
    // Initialization code
    [super awakeFromNib];
        
    [self.textView setContentOffset:CGPointZero animated:NO];
    self.textView.delegate = self;
}

- (void)setData:(id)data delegate:(id)delegate {
    
    _delegate = delegate;
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        if ([data[@"data"] isKindOfClass:[DYAddContentTextCellModel class]]) {
            DYAddContentTextCellModel *model = data[@"data"];
            _model = model;
            _placeholderLabel.text = model.tip;
            _textView.text = model.content;

            _placeholderLabel.hidden = model.content.length > 0 ? YES : NO;
            
            if (model.content.length > model.max.integerValue) {
                model.content = [model.content substringToIndex:model.max.integerValue];
            }
        }
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    _placeholderLabel.hidden = textView.text.length > 0 ? YES : NO;
    if (_delegate && [_delegate respondsToSelector:@selector(addContentTextCell:textView:)]) {
        [_delegate addContentTextCell:self textView:textView];
    }
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    _placeholderLabel.hidden = textView.text.length > 0 ? YES : NO;
    if (_delegate && [_delegate respondsToSelector:@selector(addContentTextCell:textView:)]) {
        [_delegate addContentTextCell:self textView:textView];
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger res = [new length];
    
    _placeholderLabel.hidden = new.length > 0 ? YES : NO;

    if(res <= _model.max.integerValue){
        return YES;
    } else {
        _textView.text = [new substringToIndex:_model.max.integerValue - 1];
        return NO;
    }
}

@end


#pragma mark - Model

@implementation DYAddContentTextCellModel

+ (DYAddContentTextCellModel *)ittemModelWithTitle:(NSString *)title content:(NSString *)content tip:(NSString *)tip max:(NSString *)max {
    DYAddContentTextCellModel *model = [DYAddContentTextCellModel new];
    model.title = kSafeString(title);
    model.content = kSafeString(content);
    model.tip = kSafeString(tip);
    model.max = kSafeString(max);
    return model;
}

@end
